package hn.cch.servlet.servlet;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.AsyncContext;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

public class ServletUtils {

    private static final Logger logger = LoggerFactory.getLogger(ServletUtils.class);

    public void asyncRun(HttpServletResponse response, AsyncContext asyncContext) {
        try {
            Thread.sleep(1000);
            response.setContentType("text/plain");
            PrintWriter writer = asyncContext.getResponse().getWriter();
            writer.println("HelloAsync");
        } catch (Exception e) {
            logger.error("error:", e);
        } finally {
            logger.info("complete");
            asyncContext.complete();
        }

    }

    public void asyncRead(AsyncContext asyncContext) {
        try {
            // 读取请求内容是阻塞的
            final ServletInputStream inputStream = asyncContext.getRequest().getInputStream();
            byte[] buffer = new byte[1024];
            int total = 0;
            int size = 0;
            StringBuffer stringBuffer = new StringBuffer();
            while ((size = inputStream.read(buffer)) > 0) {
                total += size;
                stringBuffer.append(new String(buffer));
            }
            logger.info("req:{}", stringBuffer);
        } catch (Exception e) {
            logger.error("error:", e);
        }
    }
}
